// const parseString = require('xml2js').parseString;
const {baseUrl} = require('@/config/config');

const regularCheck = {
    ipCheck: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
    userCheck: /^[a-zA-Z0-9_-]{4,16}$/,
};

// const xml2js = (xml) => new Promise((resolve, reject) => {
//     parseString(xml, {explicitArray: false}, function (err, result) {
//         resolve(result);
//     });
// });

//fetch api
const api = (url, data) => {
    url = url.startsWith("\/") ? url.substr(1) : url;
    return fetch(`${'http://' + baseUrl}/${url}`, {
        credentials: 'include',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    }).then(res => res.json())
}
//时间戳转日期
const dateFormat = (timeStamp, format) => {
    timeStamp = Number(timeStamp);
    if (isNaN(timeStamp) || timeStamp % 1 !== 0) { //确保是整数
        throw new Error("illegal timeStamp");
    }
    let date = new Date(timeStamp);
    if (!date || date.toUTCString() == "Invalid Date") {
        return "";
    }
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
};
//版本号比较，检测版本是否需要升级
const checkVersion = (current, latest) => {
    console.warn(current, latest)
    if(typeof current ==="string"){
        current = current.replace("'","");
        latest = latest.replace("'","");
    }
    if (current === latest) {
        return 1;//版本无更新
    } else {
        const curVersionNum = current.split(".");
        const latestVersionNum = latest.split(".");
        const [current1, current2, current3] = curVersionNum;
        const [latest1, latest2, latest3] = latestVersionNum;

        if (current1 < latest1 || current2 < latest2) {
            return 2;//强制更新
        }
        if (current3 < latest3) {
            return 3;//小版本可选升级
        }
        return 0;
    }
}

export {
    // xml2js,
    api,
    regularCheck,
    dateFormat,
    checkVersion
}



